#!/usr/bin/python
# -*- coding: utf-8 -*-
import getopt
import sys
import socket
import time
from datetime import datetime
"""
tcp ping of an instance
ping vip
ping physical ip
ping slave ip
"""

help = """
        -i instance
        -p port
        -v vip
        -h physical ip  
    """

#print sys.argv[1:]
opts, args = getopt.getopt(sys.argv[1:], 'i:p:h:v:t:')
(ins_name, host, port, vip, time_thres) = ('','','','', '0')
for optn, optv in opts:
    if optn == '-i':
        ins_name = optv
    elif optn == '-p':
        port = optv
    elif optn == '-h':
        host = optv
    elif optn == '-v':
        vip = v
    elif optn == '-t':
        time_thres = optv

print "test connect time to %s:%s" % (host, port)

def conn_tcp(host, port):
    """
    open a tcp connection to host:port
    return conn time
    """
    (t1, t2, t3, te, conn_time, close_time, err) = (0,0,0,0,0,0,'')
    
    try:
        t1 = time.time()
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(30)
        s.connect((host, int(port)))
        t2 = time.time()
        s.close()
        t3 = time.time()
    except Exception, e:
        err = e
        te = time.time()

    if t2 > 0:
        conn_time = t2 - t1
    if t3 > 0:
        close_time = t3 - t2
    if te > 0:
        if t2 > 0:
            pass
        else:
            conn_time = te - t1
    return (conn_time, close_time, err)
            
def current_time():
    t = datetime.fromtimestamp(time.time())
    return t.strftime('%Y%m%d %H:%M:%S')

def ping_ins(host, port, timeout):
    i = 0
    while True:
        (conn_time, close_time, err) = conn_tcp(host,port)
        i = i + 1
        if conn_time + close_time > timeout:
            t = current_time()
            print "%s %.6f %s" %(t, conn_time, err)
        else:
            if i % 60 == 0:
                t = current_time()
                print '.', t
                sys.stdout.flush()
            else:
                sys.stdout.write('.')
        time.sleep(1)

if __name__ == '__main__':
    ping_ins(host, port, int(time_thres))
